<?php

/* 定义like语句转换为in语句的条件 */
define('MAX_ID_NUM_OF_IN', 10000); // IN语句的最大ID数
define('MAX_HIT_RATE', 0.05);      // 最大命中率（满足条件的记录数除以总记录数）
define('MAX_STAT_PRICE', 10000);   // 最大统计价格
define('PRICE_INTERVAL_NUM', 5);   // 价格区间个数
define('MIN_STAT_STEP', 50);       // 价格区间最小间隔
define('NUM_PER_PAGE', 24);        // 每页显示数量
define('ENABLE_SEARCH_CACHE', true); // 启用商品搜索缓存
define('SEARCH_CACHE_TTL', 3600);  // 商品搜索缓存时间

class SearchApp extends MallbaseApp
{
    var $_goods_mod;
    var $_store_mod; 
	var $_gcategory_mod;
	var $_attribute_mod;
	var $_goodsattr_mod;
    var $_scategory_mod;
    var $_sgrade_mod;

    /* 构造函数 */
    function __construct()
    {
         $this->SearchApp();
    }

    function SearchApp()
    {
        parent::__construct();

        $this->_goods_mod =& m('goods');
        $this->_store_mod =& m('store');
		$this->_gcategory_mod =& bm('gcategory');
		$this->_attribute_mod =& m('attribute');
		$this->_goodsattr_mod =& m('goodsattr');
        $this->_scategory_mod =& m('scategory');
        $this->_sgrade_mod =& m('sgrade');
    }
    /* 搜索商品 */
    function index()
    { 
        
        // 查询参数
        $param = $this->_get_query_param();
        if (isset($param['cate_id']) && $param['layer'] === false)
        {
            $this->show_warning('no_such_category');
            return;
        }

        /* 筛选条件 */
        $this->assign('filters', $this->_get_filter($param));


        /* 排序 */
        $order_arr = $this->_get_goods_orders();
        $order =  isset($_GET['order']) && isset($order_arr[$_GET['order']])? $order_arr[$_GET['order']] : 'g.add_time desc';
        $this->assign('orders', trim($_GET['order']));

        /* 分页信息 */
        $page = $this->_get_page(NUM_PER_PAGE);       
        
        /* 商品列表 */
        $conditions = $this->_get_goods_conditions($param);
        $goods_list = $this->_goods_mod->find(array(
            'conditions' => $conditions,
            'fields'     => 'g.store_id, g.goods_name, g.start_stock, g.cate_id, g.price, g.is_hot, g.default_image, g.brand, s.store_name',
            'join'       => 'belongs_to_store, has_goodsstatistics',  
            'order'      => $order,
            'count'      => true,
            'limit'      => $page['limit'],
        ));    
        foreach ($goods_list as $key => $goods)
        {
            empty($goods['default_image']) && $goods_list[$key]['default_image'] = Conf::get('default_goods_image');
        }
        $page['item_count'] = $this->_goods_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);//分页数据
        $this->assign('goods_list', $goods_list);//商品列表

        /* 当前位置 */
        $cate_id = isset($param['cate_id']) ? $param['cate_id'] : 0;
        $gcategory_list = $this->_get_one_gcategory($cate_id,$this->_list_gcategory());
        /*如果是最后一级分类则获取分类的属性*/
        if(empty($gcategory_list['children']))
        {
            $attr_value = '';
            $goods_attr = $this->_get_gcategory_attribute($cate_id);
            if(isset($param['attr_value']))
            {
                $attr_value = $param['attr_value'];
            }
            else
            {
                $attr_count = count($goods_attr['attr_data']);
                for($i=1;$i<=$attr_count;$i++)
                {
                    if($i==$attr_count)
                    {
                        $attr_value .= '0';
                    }
                    else
                    {
                        $attr_value .= '0.';
                    }
                    
                }
            }
            $goods_attr['attr_data'] = $this->sort_price($goods_attr['attr_data']);
            $this->assign('goods_attr',$goods_attr['attr_data']);//分类的属性
            $this->assign('attr_value',$attr_value);//分类的属性
        }
        $this->assign('curlocal_gcategory', $this->_get_curlocal_gcategory($cate_id));//当前分类所有的上级分类树
        $this->assign('gcategory_list', $gcategory_list);//当前分类的同级分类和子分类树
        $recommend_mod =& m('recommend');
        $this->assign('recommended_goods', $recommend_mod->get_recommended_goods(16, 3));//推荐商品
        /* 浏览历史 */
		$goods_history = $this->_get_goods_history();
		$this->assign('goods_history',$goods_history);
        /* 我们为您推荐商品获取浏览历史最新一个商品同一级分类的最新的10个商品 */
        $parent_id = $goods_history[0]['cate_id_1'];
		if($parent_id){
			$com_list = $this->_goods_mod->find(array(
                'fields'=> 'goods_id,goods_name,price,cate_id,default_image',
				'conditions' => "if_show = 1 AND closed = 0 AND state = 1 AND  cate_id_1= " .$parent_id,
				'order'      => " goods.add_time desc",
                'join'       => 'belongs_to_store',
				'limit'      => "10",
			));
		}
        $keyword = isset($_GET['keyword']) ? trim(strip_tags($_GET['keyword'])) : '';
		$this->assign('com_list',$com_list);
        $this->assign('param',$param);
        $this->assign('is_leaf',$this->_gcategory_mod->is_leaf($cate_id));
        $this->assign('search_type',$_GET['act']);
        $this->assign('search_keyword',$keyword);
             
                
        /* 配置seo信息 */
        $this->_config_seo($this->_get_seo_info('goods', $cate_id));
        $this->import_resource('indexlist.js');
        $this->display('search.goods.html');
    }
    /* 按品牌搜索商品 */
    function brand()
    {
        $this->index();       
    }    

    /* 搜索店铺 */
    function store()
    {
        /* 取得该分类及子分类cate_id */
        $cate_id = empty($_GET['cate_id']) ? 0 : intval($_GET['cate_id']);
        $keyword = isset($_GET['keyword']) ? trim(strip_tags($_GET['keyword'])) : '';
        $cate_ids=array();
        $condition_id='';
        if ($cate_id > 0)
        {
            $cate_ids = $this->_scategory_mod->get_descendant($cate_id);
        }

        /* 店铺分类检索条件 */
        $condition_id=implode(',', $cate_ids);
        $condition_id && $condition_id = ' AND cate_id IN(' . $condition_id . ')';

        /* 其他检索条件 */
        $conditions = $keyword ? " AND store_name LIKE '%{$keyword}%'" : "";

        //$regions = $this->_store_mod->list_regions();
        $page   =   $this->_get_page(10);   //获取分页信息
//        $stores = $this->_store_mod->findAll(array(
//            'fields'=> 's.store_name,s.owner_name,s.im_qq,s.im_ww,s.store_logo',
//            'conditions'  => 'state = ' . STORE_OPEN . $condition_id . $conditions,
//            'limit'   =>$page['limit'],
//            'order'   => empty($_GET['order']) || !in_array($_GET['order'], array('credit_value desc')) ? 'recommended desc ,sort_order' : $_GET['order'],
//            'count'   => true   //允许统计
//        ));
        $condition = 'g.goods_id is not null AND g.closed = 0 AND g.if_show = 1 AND s.state = ' . STORE_OPEN . $condition_id . $conditions;
        
        $order = empty($_GET['order']) || !in_array($_GET['order'], array('credit_value desc')) ? 's.recommended desc ,s.sort_order, s.store_id' : $_GET['order'];
        $sql = "select distinct s.store_id,s.store_name,s.owner_name,s.im_qq,s.im_ww,s.store_logo from wl_store s  
                left join wl_goods g on s.store_id=g.store_id where "  . $condition . " order by {$order} limit {$page['limit']}";
                
        $stores = $this->_store_mod->getAll($sql);
        foreach ($stores as $key => $store)
        {
            //店铺logo
            empty($store['store_logo']) && $stores[$key]['store_logo'] = Conf::get('default_store_logo');

            //商品数量
            //$stores[$key]['goods_count'] = $this->_goods_mod->get_count_of_store($store['store_id']);

            //等级图片
//            $step = intval(Conf::get('upgrade_required'));
//            $step < 1 && $step = 5;
//            $stores[$key]['credit_image'] = $this->_view->res_base . '/images/' . $this->_store_mod->compute_credit($store['credit_value'], $step);
            $stores[$key]['goods'] = $this->_goods_mod->find(array(          
                'fields'=> 'goods_id, goods_name, default_image, price',
                'conditions' => 'closed = 0 AND if_show = 1 AND store_id = ' . $store['store_id'],
                'count' => true,
                'order' => 'add_time DESC',
                'limit' => 5,
            ));
            foreach ($stores[$key]['goods'] as $k => $goods)
            {
                empty($goods['default_image']) && $stores[$key]['goods'][$k]['default_image'] = Conf::get('default_goods_image');
            }

        }
        
        $countsql = "select count(distinct s.store_id) from wl_store s left join wl_goods g on s.store_id=g.store_id where " . $condition;
        $page['item_count']= $this->_store_mod->getOne($countsql);   //获取统计数据
        $this->_format_page($page);

        /* 当前位置 */
        $this->_curlocal($this->_get_store_curlocal($cate_id));
        //$scategorys = $this->_list_scategory();
        $this->import_resource('indexlist.js');
        $this->assign('stores', $stores);
        //$this->assign('regions', $regions);
        $this->assign('cate_id', $cate_id);
        //$this->assign('scategorys', $scategorys);
        $this->assign('page_info', $page);
        $this->assign('search_type',$_GET['act']);
        $this->assign('search_keyword',$keyword);
        /* 配置seo信息 */
        $this->_config_seo($this->_get_seo_info('store', $cate_id));
        $this->display('search.store.html');
    }


     /* 取得店铺分类 */
    function _list_scategory()
    {
        $scategories = $this->_scategory_mod->get_list(-1,true);
        import('tree.lib');
        $tree = new Tree();
        $tree->setTree($scategories, 'cate_id', 'parent_id', 'cate_name');
        return $tree->getArrayList(0);
    }
    
    /* 取得商品分类 */
    function _list_gcategory()
    {
        $cache_server =& cache_server();
        $key = 'search_goods_category';
        $data = $cache_server->get($key);
        if ($data === false)
        {
            $gcategory_mod =& bm('gcategory', array('_store_id' => 0));
            $gcategories = $gcategory_mod->get_list(-1,true);
    
            import('tree.lib');
            $tree = new Tree();
            $tree->setTree($gcategories, 'cate_id', 'parent_id', 'cate_name');
            $data = $tree->getArrayListWithId(0);

            $cache_server->set($key, $data, 3600);
        }

        return $data;
    }
    
    /**
     *  取得某个商品分类的同级分类与子分类
     *  @author  yanghj 2014.07.16
     *  @param int $cate_id    商品分类ID
     *  @param array $arr      商品的所有的分类
     *  @return array
     */
    function _get_one_gcategory($cate_id,$arr=array())
    {
        static $data = null;
        if(!$cate_id || !$arr)
        {
           return ; 
        }       
        if(is_array($arr))
        {
            foreach($arr as $key=>$val)
            {
                if($cate_id == $val['id'])
                {
                    $data['cate'] = $arr;
                    $data['children'] = $val['children'];
                    break;
                }
               else
               {
                 $this->_get_one_gcategory($cate_id,$val['children']);
               }
            }
            
        }       
        return $data;
    }
    
    /**
     *  取得当前商品分类与所有的父级分类
     *  @author  yanghj 2014.07.16
     *  @param int $cate_id    商品分类ID
     *  @param array $arr      商品的所有的分类
     *  @return array
     */
    function _get_curlocal_gcategory($cate_id)
    {
        $arr = array();
        $parents = array();
        if ($cate_id)
        {
            $parents = $this->_gcategory_mod->get_ancestor($cate_id, true);
        }
        foreach ($parents as $category)
        {
            $data = $this->_get_one_gcategory($category['cate_id'],$this->_list_gcategory());
            $arr[] = array('cate_id' => $category['cate_id'],'cate_name' => $category['cate_name'], 'category' => $data['cate']);
        }
        return $arr;
     }
     
     /**
     *  取得当前商品分类的属性
     *  @author  yanghj 2014.07.16
     *  @param int $cate_id    商品分类ID
     *  @param array $arr      商品分类关联商品的属性
     */
    function _get_gcategory_attribute($cate_id)
    {   $cate_id = intval($cate_id);
        if($cate_id<1)
        {
            return ;
        }
        $cache_server =& cache_server();
        $key = 'page_category_attribute'.$cate_id;
        $data = $cache_server->get($key);
        if ($data === false)
        {
            $sql = "SELECT attr_id FROM {$this->_attribute_mod->table}  WHERE cate_id = {$cate_id} AND attr_index = 1";
            $attr_ids = $this->_attribute_mod->getCol($sql);
            if($attr_ids)
            {
                $conditions = 'attr_id' . db_create_in($attr_ids).' AND g.if_show = 1 AND g.closed = 0 ';
                $goods_attr = $this->_goodsattr_mod->find(array(
            		'fields'=> 'this.gattr_id,this.attr_name,this.attr_value,this.attr_id,this.goods_id',
            		'conditions' => $conditions." GROUP BY attr_value",
                    'join' => 'belongs_to_goods',
            		'order' => 'attr_id ASC',
    	     	));

                if($goods_attr)
                {
                    foreach($goods_attr as $key => $val)
                    {
                        $children_key = $val['gattr_id'];
                        
                        if($val['attr_value'] == "其他" || $val['attr_value'] == "其它")
                            $children_key = 0;
            
                        $attr_data[$val['attr_id']]['attr_id']   = $val['attr_id'];
                        $attr_data[$val['attr_id']]['attr_name']  = $val['attr_name'];
                        $attr_data[$val['attr_id']]['children'][$children_key]['attr_value'] = $val['attr_value'];
                        $attr_data[$val['attr_id']]['children'][$children_key]['gattr_id']   = $val['gattr_id'];
                        $attr_data[$val['attr_id']]['children'][$children_key]['goods_id']   = $val['goods_id'];
                        $attr_data[$val['attr_id']]['children'][$children_key]['attr_id']    = $val['attr_id'];     
                        krsort($attr_data[$val['attr_id']]['children']); 
                    }
                    $data['goods_attr'] = $goods_attr;
                    $data['attr_data']  = $attr_data;
                    $cache_server->set($key, $data, 3600);
                    
                }                                               
            }
            
        }

        return $data;
    }   

    function _get_goods_curlocal($cate_id)
    {
        $parents = array();
        if ($cate_id)
        {
            $parents = $this->_gcategory_mod->get_ancestor($cate_id, true);
        }

        $curlocal = array(
            array('text' => LANG::get('all_categories'), 'url' => "javascript:dropParam('cate_id')"),
        );
        foreach ($parents as $category)
        {
            $curlocal[] = array('text' => $category['cate_name'], 'url' => "javascript:replaceParam('cate_id', '" . $category['cate_id'] . "')");
        }
        unset($curlocal[count($curlocal) - 1]['url']);

        return $curlocal;
    }

    function _get_store_curlocal($cate_id)
    {
        $parents = array();
        if ($cate_id)
        {
            $this->_scategory_mod->get_parents($parents, $cate_id);
        }

        $curlocal = array(
            array('text' => LANG::get('all_categories'), 'url' => url('app=category&act=store')),
        );
        foreach ($parents as $category)
        {
            $curlocal[] = array('text' => $category['cate_name'], 'url' => url('app=search&act=store&cate_id=' . $category['cate_id']));
        }
        unset($curlocal[count($curlocal) - 1]['url']);
        return $curlocal;
    }
    
    /* 取得浏览历史 */
	function _get_goods_history()
	{
		$goods_mod  =& m('goods');
		$goods_list = array();
		$goods_ids  = ecm_getcookie('goodsBrowseHistory');
		$goods_ids  = $goods_ids ? explode(',', $goods_ids) : array();
		if ($goods_ids)
		{
			$rows = $goods_mod->find(array(
			'conditions' => $goods_ids,
			'fields'     => 'goods_name,default_image,price,cate_id_1',
			));
			foreach ($goods_ids as $goods_id)
			{
				if (isset($rows[$goods_id]))
				{
					empty($rows[$goods_id]['default_image']) && $rows[$goods_id]['default_image'] = Conf::get('default_goods_image');
					$goods_list[] = $rows[$goods_id];
				}
			}
            krsort($goods_list);
		}		
		return $goods_list;
	}

    /**
     * 取得查询参数（有值才返回）
     *
     * @return  array(
     *              'keyword'   => array('aa', 'bb'),
     *              'cate_id'   => 2,
     *              'layer'     => 2, // 分类层级
     *              'brand'     => 'ibm',
     *              'region_id' => 23,
     *              'price'     => array('min' => 10, 'max' => 100),
     *          )
     */
    function _get_query_param()
    {
        static $res = null;
        if ($res === null)
        {
            $res = array();
    
            // keyword 关键词
            $keyword = isset($_GET['keyword']) ? trim(strip_tags($_GET['keyword'])) : '';
            if ($keyword != '')
            {
                //$keyword = preg_split("/[\s," . Lang::get('comma') . Lang::get('whitespace') . "]+/", $keyword);
                $tmp = str_replace(array(Lang::get('comma'),Lang::get('whitespace'),' '),',', $keyword);
                $keyword = explode(',',$tmp);
                sort($keyword);
                $res['keyword'] = $keyword;
            }
    
            // cate_id 分类
            if (isset($_GET['cate_id']) && intval($_GET['cate_id']) > 0)
            {
                $res['cate_id'] = $cate_id = intval($_GET['cate_id']);
                $res['layer']   = $this->_gcategory_mod->get_layer($cate_id, true);
            }
    
            // attr 属性
            if (isset($_GET['attr_value']))
            {
                $attr = trim(strip_tags($_GET['attr_value']));
                $attr = preg_match('/^[\d\.]+$/',$attr) ? $attr : '';
                $res['attr_value'] = $attr;
            }
			// spec 规格
            if (isset($_GET['spec_value']))
            {
                $spec = trim($_GET['spec_value']);
                $res['spec_value'] = $spec;
            }
			// start_stock  起订量
            if (!empty($_GET['start_stock']))
            {	
                $start_stock = intval($_GET['start_stock']);
                $res['start_stock'] = array(
                    'max' => $start_stock
                );
            }
            // is_hot  热销商品
            if ($_GET['is_hot']==1)
            {
                $res['is_hot'] = intval($_GET['is_hot']);
            }
    
            // price  价格区间
            if (isset($_GET['price']))
            {
                $arr = explode('-', $_GET['price']);
                $min = abs(floatval($arr[0]));
                $max = abs(floatval($arr[1]));
                if ($min * $max > 0 && $min > $max)
                {
                    list($min, $max) = array($max, $min);
                }
    
                $res['price'] = array(
                    'min' => $min,
                    'max' => $max
                );
            }
        }

        return $res;
    }

    /**
     * 取得过滤条件
     */
    function _get_filter($param)
    {
        static $filters = null;
        if ($filters === null)
        {
            $filters = array();
            if (isset($param['keyword']))
            {
                $keyword = join(' ', $param['keyword']);
                $filters['keyword'] = array('key' => 'keyword', 'name' => LANG::get('keyword'), 'value' => $keyword);
            }
            
			isset($param['spec_value']) && $filters['spec_value'] = array('key' => 'spec_value', 'name' => LANG::get('attr_value'), 'value' => $param['spec_value']);
			isset($param['start_stock']) && $filters['start_stock'] = array('key' => 'start_stock', 'name' => LANG::get('start_stock'), 'value' => $param['start_stock']);
			//isset($param['is_hot']) && $filters['is_hot'] = array('key' => 'is_hot', 'name' => LANG::get('is_hot'), 'value' => $param['is_hot']);
            if (isset($param['price']))
            {
                $min = $param['price']['min'];
                $max = $param['price']['max'];
                if ($min <= 0)
                {
                    $filters['price'] = array('key' => 'price', 'name' => LANG::get('price'), 'value' => LANG::get('le') . ' ' . price_format($max));
                }
                elseif ($max <= 0)
                {
                    $filters['price'] = array('key' => 'price', 'name' => LANG::get('price'), 'value' => LANG::get('ge') . ' ' . price_format($min));
                }
                else
                {
                    $filters['price'] = array('key' => 'price', 'name' => LANG::get('price'), 'value' => price_format($min) . ' - ' . price_format($max));
                }
            }
            if(isset($param['attr_value']) && !empty($param['attr_value']) && $param['cate_id']>0)
            {
                $attr = $this->_get_gcategory_attribute($param['cate_id']);
                $goods_attr = $attr['goods_attr'];
                $filter_attr = explode('.', $param['attr_value']);  
                if (!empty($filter_attr))
                {
                    foreach ($filter_attr AS $k => $v)
                    {
                        if (is_numeric($v) && $v !=0 &&isset($goods_attr[$v]))
                        {
                            $filters['attr_value'][] = array('key' => 'attr_value', 'name' => $goods_attr[$v]['attr_value'], 'value' => $goods_attr[$v]['gattr_id'], 'attr_id'=> $goods_attr[$v]['attr_id']);
                        }
                    }
                    
                }
            }
            
        }
        
            

        return $filters;
    }

    /**
     * 取得查询条件语句
     *
     * @param   array   $param  查询参数（参加函数_get_query_param的返回值说明）
     * @return  string  where语句
     */
    function _get_goods_conditions($param)
    {
        /* 组成查询条件 */
        $conditions = " g.if_show = 1 AND g.closed = 0 AND s.state = 1"; // 上架且没有被禁售，店铺是开启状态,
        /*关键词查询*/
        if (isset($param['keyword']))
        {
            $conditions .= $this->_get_conditions_by_keyword($param['keyword'], ENABLE_SEARCH_CACHE);
        }
        /*分类查询*/
        if (isset($param['cate_id']))
        {
            $conditions .= " AND g.cate_id_{$param['layer']} = '" . $param['cate_id'] . "'";
        }
        /*起订量查询*/
        if (isset($param['start_stock']))
        {
            $conditions .= " AND g.start_stock <= '" . $param['start_stock'] . "'";
        }
        /*热销商品查询*/
		if ($param['is_hot']==1)
        {
            $conditions .= " AND g.is_hot = 1";
        }        
        /*价格查询*/
        if (isset($param['price']))
        {
            $min = $param['price']['min'];
            $max = $param['price']['max'];
            $min > 0 && $conditions .= " AND g.price >= '$min'";
            $max > 0 && $conditions .= " AND g.price <= '$max'";
        }
        /*分类查询*/
        if (isset($param['attr_value']) && !empty($param['attr_value']) && $param['cate_id']>0)
        {
            $attr = $this->_get_gcategory_attribute($param['cate_id']);
            $goods_attr = $attr['goods_attr'];
            $filter_attr = explode('.', $param['attr_value']);
            if (!empty($filter_attr))
            {
                $ext_sql = "SELECT DISTINCT(b.goods_id) FROM " . $this->_goodsattr_mod->table . " AS a, " . $this->_goodsattr_mod->table . " AS b " .  "WHERE ";
                $ext_group_goods = array();
    
                foreach ($filter_attr AS $k => $v)                      // 查出符合所有筛选属性条件的商品id */
                {
                    if (is_numeric($v) && $v !=0 &&isset($goods_attr[$v]))
                    {
                        $sql = $ext_sql . "b.attr_value = a.attr_value AND b.attr_id = " . $goods_attr[$v]['attr_id'] ." AND a.gattr_id = " . $v;
                        $ext_group_goods = $this->_goodsattr_mod->db->getColCached($sql);
                        $conditions .= ' AND ' . db_create_in($ext_group_goods, 'g.goods_id');
                    }
                }
            }
        }

        return $conditions;
    }

    /**
     * 根据查询条件取得分组统计信息
     *
     * @param   array   $param  查询参数（参加函数_get_query_param的返回值说明）
     * @param   bool    $cached 是否缓存
     * @return  array(
     *              'total_count' => 10,
     *              'by_category' => array(id => array('cate_id' => 1, 'cate_name' => 'haha', 'count' => 10))
     *              'by_brand'    => array(array('brand' => brand, 'count' => count))
     *              'by_region'   => array(array('region_id' => region_id, 'region_name' => region_name, 'count' => count))
     *              'by_price'    => array(array('min' => 10, 'max' => 50, 'count' => 10))
     *          )
     */
    function _get_group_by_info($param, $cached)
    {
        $data = false;

        if ($cached)
        {
            $cache_server =& cache_server();
            $key = 'group_by_info_' . var_export($param, true);
            $data = $cache_server->get($key);
        }

        if ($data === false)
        {
            $data = array(
                'total_count' => 0,
                'by_category' => array(),
                'by_brand'    => array(),
                'by_region'   => array(),
                'by_price'    => array()
            );

            $table = " {$this->_goods_mod->table} g LEFT JOIN {$this->_store_mod->table} s ON g.store_id = s.store_id";
            $conditions = $this->_get_goods_conditions($param);
            $sql = "SELECT COUNT(*) FROM {$table} WHERE" . $conditions;
            $total_count = $this->_goods_mod->getOne($sql);
            if ($total_count > 0)
            {
                $data['total_count'] = $total_count;
                /* 按分类统计 */
                $cate_id = isset($param['cate_id']) ? $param['cate_id'] : 0;
                $sql = "";
                if ($cate_id > 0)
                {
                    $layer = $param['layer'];
                    if ($layer < 4)
                    {
                        $sql = "SELECT g.cate_id_" . ($layer + 1) . " AS id, COUNT(*) AS count FROM {$table} WHERE" . $conditions . " AND g.cate_id_" . ($layer + 1) . " > 0 GROUP BY g.cate_id_" . ($layer + 1) . " ORDER BY count DESC";
                    }
                }
                else
                {
                    $sql = "SELECT g.cate_id_1 AS id, COUNT(*) AS count FROM {$table} WHERE" . $conditions . " AND g.cate_id_1 > 0 GROUP BY g.cate_id_1 ORDER BY count DESC";
                }

                if ($sql)
                {
                    $children = $this->_gcategory_mod->get_children($cate_id, true);
                    $res = $this->_goods_mod->db->query($sql);
                    while ($row = $this->_goods_mod->db->fetchRow($res))
                    {
                        $data['by_category'][$row['id']] = array(
                            'cate_id'   => $row['id'],
                            'cate_name' => $children[$row['id']]['cate_name'],
                            'count'     => $row['count']
                        );
                    }
                }

                /* 按品牌统计 */
                $sql = "SELECT g.brand, COUNT(*) AS count FROM {$table} WHERE" . $conditions . " AND g.brand > '' GROUP BY g.brand ORDER BY count DESC";
                $by_brands = $this->_goods_mod->db->getAllWithIndex($sql, 'brand');
                
                /* 滤去未通过商城审核的品牌 */
                if ($by_brands)
                {
                    $m_brand = &m('brand');
                    $brand_conditions = db_create_in(addslashes_deep(array_keys($by_brands)), 'brand_name');
                    $brands_verified = $m_brand->getCol("SELECT brand_name FROM {$m_brand->table} WHERE " . $brand_conditions . ' AND if_show=1');
                    foreach ($by_brands as $k => $v)
                    {
                        if (!in_array($k, $brands_verified))
                        {
                            unset($by_brands[$k]);
                        }
                    }
                }
                $data['by_brand'] = $by_brands;
                
                
                /* 按地区统计 */
                $sql = "SELECT s.region_id, s.region_name, COUNT(*) AS count FROM {$table} WHERE" . $conditions . " AND s.region_id > 0 GROUP BY s.region_id ORDER BY count DESC";
                $data['by_region'] = $this->_goods_mod->getAll($sql);

                /* 按价格统计 */
                if ($total_count > NUM_PER_PAGE)
                {
                    $sql = "SELECT MIN(g.price) AS min, MAX(g.price) AS max FROM {$table} WHERE" . $conditions;
                    $row = $this->_goods_mod->getRow($sql);
                    $min = $row['min'];
                    $max = min($row['max'], MAX_STAT_PRICE);
                    $step = max(ceil(($max - $min) / PRICE_INTERVAL_NUM), MIN_STAT_STEP);
                    $sql = "SELECT FLOOR((g.price - '$min') / '$step') AS i, count(*) AS count FROM {$table} WHERE " . $conditions . " GROUP BY i ORDER BY i";
                    $res = $this->_goods_mod->db->query($sql);
                    while ($row = $this->_goods_mod->db->fetchRow($res))
                    {
                        $data['by_price'][] = array(
                            'count' => $row['count'],
                            'min'   => $min + $row['i'] * $step,
                            'max'   => $min + ($row['i'] + 1) * $step,
                        );
                    }
                }
            }

            if ($cached)
            {
                $cache_server->set($key, $data, SEARCH_CACHE_TTL);
            }
        }

        return $data;
    }

    /**
     * 根据关键词取得查询条件（可能是like，也可能是in）
     *
     * @param   array       $keyword    关键词
     * @param   bool        $cached     是否缓存
     * @return  string      " AND (0)"
     *                      " AND (goods_name LIKE '%a%' AND goods_name LIKE '%b%')"
     *                      " AND (goods_id IN (1,2,3))"
     */
    function _get_conditions_by_keyword($keyword, $cached)
    {
        $conditions = false;

        if ($cached)
        {
            $cache_server =& cache_server();
            $key1 = 'query_conditions_of_keyword_' . join("\t", $keyword);
            $conditions = $cache_server->get($key1);
        }

        if ($conditions === false)
        {
            /* 组成查询条件 */
            $conditions = array();
            foreach ($keyword as $word)
            {
                $conditions[] = "(g.goods_name LIKE '%{$word}%' OR g.brand LIKE '%{$word}%')";
            }
            $conditions = join(' AND ', $conditions);

            /* 取得满足条件的商品数 */
            $sql = "SELECT COUNT(*) FROM {$this->_goods_mod->table} g WHERE " . $conditions;
            $current_count = $this->_goods_mod->getOne($sql);
            if ($current_count > 0)
            {
                if ($current_count < MAX_ID_NUM_OF_IN)
                {
                    /* 取得商品表记录总数 */
                    $cache_server =& cache_server();
                    $key2 = 'record_count_of_goods';
                    $total_count = $cache_server->get($key2);
                    if ($total_count === false)
                    {
                        $sql = "SELECT COUNT(*) FROM {$this->_goods_mod->table}";
                        $total_count = $this->_goods_mod->getOne($sql);
                        $cache_server->set($key2, $total_count, SEARCH_CACHE_TTL);
                    }

                    /* 不满足条件，返回like */
                    if (($current_count / $total_count) < MAX_HIT_RATE)
                    {
                        /* 取得满足条件的商品id */
                        $sql = "SELECT goods_id FROM {$this->_goods_mod->table} g WHERE " . $conditions;
                        $ids = $this->_goods_mod->getCol($sql);
                        $conditions = 'g.goods_id' . db_create_in($ids);
                    }
                }
            }
            else
            {
                /* 没有满足条件的记录，返回0 */
                $conditions = "0";
            }

            if ($cached)
            {
                $cache_server->set($key1, $conditions, SEARCH_CACHE_TTL);
            }
        }

        return ' AND (' . $conditions . ')';
    }

    /* 商品排序方式 */
    function _get_orders()
    {
        return array(
            ''                  => Lang::get('select_pls'),
            'sales desc'        => Lang::get('sales_desc'),
            'credit_value desc' => Lang::get('credit_value_desc'),
            'price asc'         => Lang::get('price_asc'),
            'price desc'        => Lang::get('price_desc'),
            'views desc'        => Lang::get('views_desc'),
            'add_time desc'     => Lang::get('add_time_desc'),
        );
    }
    
    /* 商品排序方式 */
    function _get_goods_orders()
    {
        return array(
            'sales-desc'        => 'sales desc',
            'sales-asc'         => 'sales asc',
            'price-asc'         => 'g.price asc',
            'price-desc'        => 'g.price desc',
            'add_time-desc'     => 'g.add_time desc',
            'add_time-asc'      => 'g.add_time asc',
        );
    }
    
    function _get_seo_info($type, $cate_id)
    {
        $seo_info = array(
            'keywords'    => '艺术摆件,仿真花饰,餐饮用具,家居用品,特色家具',
            'description' => '万菱家饰网提供各种艺术摆件、仿真花饰、餐饮用具、家居用品、特色家具，款式风格选择多，促销优惠最贴心。'
        );
        switch ($type)
        {
            case 'goods':   
                if ($cate_id)
                {
                    $parents = $this->_gcategory_mod->get_ancestor($cate_id, true);
                    $parents = array_reverse($parents);
                    foreach ($parents as $key => $cate)
                        $seo_info['title'] .= $cate['cate_name'] . '-';                    
                    $seo_info['title'] .= Conf::get("site_name");
                }else
                    $seo_info['title'] = '搜索商品-艺术摆件、仿真花饰、餐饮用具、家居用品、特色家具-'.Conf::get("site_name");
                break;
            case 'store':
                $seo_info['title'] = '搜索店铺-艺术摆件、仿真花饰、餐饮用具、家居用品、特色家具-'.Conf::get("site_name");
        }
        /*$parents = array(); // 所有父级分类包括本身
        switch ($type)
        {
            case 'goods':                
                if ($cate_id)
                {
                    $parents = $this->_gcategory_mod->get_ancestor($cate_id, true);
                    $parents = array_reverse($parents);
                }
                $filters = $this->_get_filter($this->_get_query_param());
                foreach ($filters as $k => $v)
                {
                    $seo_info['keywords'] .= $v['value']  . ',';
                }
                break;
            case 'store':
                if ($cate_id)
                {
                    $this->_scategory_mod->get_parents($parents, $cate_id);
                    $parents = array_reverse($parents);
                }
        }
        
        foreach ($parents as $key => $cate)
        {
            $seo_info['title'] .= $cate['cate_name'] . ' - ';
            $seo_info['keywords'] .= $cate['cate_name']  . ',';
            if ($cate_id == $cate['cate_id'])
            {
                $seo_info['description'] = $cate['cate_name'] . ' ';
            }
        }
        $seo_info['title'] .= Lang::get('searched_'. $type) . ' - ' .Conf::get('site_title');
        $seo_info['keywords'] .= Conf::get('site_title');
        $seo_info['description'] .= Conf::get('site_title');*/
        return $seo_info;
    }
    
    function sort_price($goods_attr)
    {
        $result = $goods_attr ? $goods_attr : array();
        foreach ($result as $key1 => $attr)
        {
            if($attr['attr_name'] == "价格区间"){
                foreach($attr['children'] as $key2 => $val){
                    $attr_value = str_replace("以上", "", $val['attr_value']);
                    $attr_value = explode("-", $attr_value);
                    unset($result[$key1]['children'][$key2]);
                    $result[$key1]['children'][$attr_value[0]] = $val;
                    ksort($result[$key1]['children']);
                }
            }
        }
        return $result;
    }
}

?>
